package controllers

import config.{Global, MyFile}
import play.api.libs.json.Json

import javax.inject.Inject
import play.api.mvc.{AbstractController, ControllerComponents}

import scala.concurrent.ExecutionContext

class DownloadController @Inject()(cc: ControllerComponents)(implicit exec: ExecutionContext) extends AbstractController(cc) with MyFile {

  def downloadPage = Action{implicit request=>
    Ok(views.html.download.downloadPage())
  }


  def getDownloadList = Action{implicit request=>
    val list = s"${Global.path}/download".listFile.map(_.getName)
    Ok(Json.obj("list" -> list))
  }



  def downloadGenomeFile(file: String,species:String) = Action { implicit request =>

    val files = file match {
      case "genome" => s"$species.genome.fasta.tar.gz"
      case "cds" => s"$species.cds.fasta.tar.gz"
      case "protein" => s"$species.protein.fasta.tar.gz"
      case "gff" => s"$species.gff.tar.gz"
      case "anno" => s"$species.anno.xls.tar.gz"
    }

    Ok.sendFile(s"${Global.path}/download/genome/$files".toFile).withHeaders(
      //缓存
      CACHE_CONTROL -> "max-age=3600",
      CONTENT_DISPOSITION -> s"attachment; filename=$files",
      CONTENT_TYPE -> "application/x-download"
    )

  }

  def downloadCpFile(file: String,species:String) = Action { implicit request =>
    val files = file match {
      case "cds" => s"$species.cds"
      case "protein" => s"$species.pep"
      case "gff" => s"$species.gff"
      case "anno" => s"$species.xls"
    }

    val name = "cp_" + files

    Ok.sendFile(s"${Global.path}/download/cp/$files".toFile).withHeaders(
      //缓存
      CACHE_CONTROL -> "max-age=3600",
      CONTENT_DISPOSITION -> s"attachment; filename=$name",
      CONTENT_TYPE -> "application/x-download"
    )
  }


  def downloadFile(file: String) = Action { implicit request =>
    val files = file.replaceAll("\\\\","").replaceAll("/","")


    Ok.sendFile(s"${Global.path}/download/$files".toFile).withHeaders(
      //缓存
      CACHE_CONTROL -> "max-age=3600",
      CONTENT_DISPOSITION -> s"attachment; filename=$files",
      CONTENT_TYPE -> "application/x-download"
    )
  }

}
